# -*- coding: utf-8 -*-

from openerp import models
from openerp.osv import osv, fields, orm


# 增加伙伴的客户级别、信用余额
class res_partner_ext(orm.Model):
    _inherit = "res.partner"

    #计算可用信用余额(信用额度减应收款项)
    def _compute_balance(self, cr, uid, ids, name, arg, context=None):
        res = {}
        for partner in self.browse(cr, uid, ids, context=context):
            #如果不是公司并且有母公司，则取得母公司的可用信用额度
            if partner.is_company == False and partner.parent_id:
                res[partner.id] = partner.parent_id.credit_limit - partner.parent_id.credit
            else:
                res[partner.id] = partner.credit_limit - partner.credit
                #res[partner.id] = {
                #    'balance': partner.credit_limit - partner.credit,
                #}
                #balance = partner.credit_limit - partner.credit
                #if balance != False:
                #    res[partner.id]['balance'] = balance
        return res

    _columns = {
        'grade': fields.selection([(u'代理商', u'代理商'),
                                   (u'VIP客户', u'VIP客户'),
                                   (u'经销商', u'经销商'),
                                   (u'特渠客户', u'特渠客户'),
                                   (u'跟进客户', u'跟进客户'),
                                   (u'中断客户', u'中断客户')], u'客户级别'),
        'balance': fields.function(_compute_balance, string=u'信用余额(信用额度减应收款)', type='float'),
        'short_name': fields.char(string=u'简称', size=64),
        'principal': fields.char(string=u'企业负责人', size=64),
        'qq': fields.char(string='QQ', size=32),
        'county': fields.char(string=u'县区', size=32),
        'last_contact_time': fields.datetime(string=u'最后联系时间'),
        'credit_expired_limit': fields.float(string=u'信用到期额度'),
        'credit_expired_date': fields.date(string=u'信用到期时间'),
        }

    _defaults = {
        #新建客户时，默认是公司选项
        'is_company': 1
    }

    #处理信用额度到期
    def process_credit_expired(self, cr, uid, context=None):
        today = fields.date.context_today(self, cr, uid, context=context)
        #更新小于今天的信用到期日
        update_sql = """
            update res_partner
            set credit_limit=credit_expired_limit, credit_expired_date=null
            where credit_expired_limit<>credit_limit and credit_expired_date<'%s'
        """ % (today)
        cr.execute(update_sql)
